<template>
  <main-content title="任务分类" :inner-padding="false" class="category-main-content">
    <l-r-content-index :is-drag="true">
      <template #title>
        <div class="side-title-inner">
          分类列表
          <el-button type="primary" @click="createCategory(null)" v-has="['10000101']">
            <el-icon>
              <Plus />
            </el-icon>
            <span style="margin-left: 10px">新增分类</span>
          </el-button>
        </div>
      </template>

      <template #side-content>
        <left-tree ref="LeftTreeRef" :treeData="categoryList" :treeProps="treeProps"
          :defaultExpandedKeys="defaultExpandedKeys" :disableSelect="disableSelect"
          :currentNodeKey="treeCurrentId || 'all'" @getTreeNodeId="getTreeNodeId">
          <template #tree-item="{ node, data }">
            <div :class="{ 'category-item__offline': !data.status }">
              {{ data.categoryName }}
              <span v-if="!data.status">（未启用）</span>
            </div>
          </template>
          <template #drop-down-item="{ node, data }">
            <el-dropdown-item v-if="!data.status" @click="_changeCateStatus(data)"
              v-has="['10000102']">启用分类</el-dropdown-item>
            <el-dropdown-item v-else @click="_changeCateStatus(data)" v-has="['10000103']">停用分类</el-dropdown-item>
            <el-dropdown-item @click="createCategory(data, node)" v-has="['10000104']">新增子分类</el-dropdown-item>
            <el-dropdown-item @click="editCategory(data)" v-has="['10000105']">编辑分类</el-dropdown-item>
            <el-dropdown-item @click="_deleteCate(data)" v-has="['10000106']">删除分类</el-dropdown-item>
          </template>
        </left-tree>
      </template>

      <main-content-search-bar-wrapper>
        <search-bar>
          <template #normal>
            <el-form-item label="任务名称">
              <el-input v-model="searchForm.taskName" placeholder="请输入任务名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="任务类型">
              <el-select v-model="searchForm.taskType" clearable>
                <el-option v-for="(item, index) in taskTypeList" :value="item.value" :label="item.label" :key="index">{{
                  item.label }}</el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="任务状态">
              <el-select v-model="searchForm.status" clearable>
                <el-option v-for="(item, index) in taskStatus" :label="item.label" :value="item.value" :key="index">
                </el-option>
              </el-select>
            </el-form-item>
            <!--            <ins-cascader-filter @change="(insId) => searchForm.insId = insId"></ins-cascader-filter>-->
            <el-form-item>
              <el-button type="primary" @click="refreshTaskList">查询</el-button>
              <el-button type="primary" @click="createTask" v-has="['10000107']">新增任务</el-button>
              <el-button type="primary" @click="toSetGroup" v-has="['10000108']">批量修改分组</el-button>
              <!-- TODO 加权限 -->
              <el-button type="primary" @click="showExportData = true">导出</el-button>
            </el-form-item>

          </template>
        </search-bar>
      </main-content-search-bar-wrapper>

      <div v-if="selectionList.length" class="">已选 {{ selectionList.length }} 条</div>

      <layout-table ref="taskTableRef" url="/merchant/task/info/pageTaskInfo" row-key="id" :param="searchForm"
        :hide-init="true" :set-search="taskTableManullySearch" @selection-change="selectionChange">
        <el-table-column type="selection" :reserve-selection="true" width="55" />
        <el-table-column label="任务名称" prop="taskName" min-width="180"></el-table-column>
        <el-table-column label="任务描述" prop="taskDescription" min-width="200"></el-table-column>
        <el-table-column label="所属分类" prop="categoryIds" min-width="150">
          <template #default="scope">
            {{ getCategoryName(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column label="任务类型" prop="taskType" width="120">
          <template #default="scope">
            {{ getTaskTypeLabel(scope.row.taskType) }}
          </template>
        </el-table-column>
        <el-table-column label="对接系统" prop="externalMerchantConfigId" width="180">
          <template #default="scope">
            {{ getExternalConfigLabel(scope.row.externalMerchantConfigId) }}
          </template>
        </el-table-column>
        <el-table-column label="任务编码" prop="taskCode" width="120"></el-table-column>
        <el-table-column label="跳转连接" prop="taskUrl" min-width="180" max-width="300"></el-table-column>
        <el-table-column label="任务状态" prop="status" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.status" v-loading="scope.row.statusLoading"
              :before-change="() => _changeTaskStatus(scope.row)" active-text="启用" inactive-text="未启用" inline-prompt
              :active-value="1" :inactive-value="0">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <el-button link type="primary" @click="editTask(scope.row)" v-has="['10000109']">编辑</el-button>
            <el-button link type="danger" @click="_deleteTask(scope.row)" v-has="['10000110']">删除</el-button>
            <el-button link type="primary" @click="goTaskRecord(scope.row)" v-has="['10000111']">任务记录</el-button>
          </template>
        </el-table-column>
      </layout-table>
    </l-r-content-index>

    <task-edit-dialog v-model:show="isShowTaskEditDialog" :mode="editDialogMode" :row-data="operatingRow"
      @done="refreshTaskList">
    </task-edit-dialog>

    <category-edit-dialog v-model:show="isShowCategoryEditDialog" :row-data="operatingRow" :mode="editDialogMode"
      @done="refresh">
    </category-edit-dialog>

    <set-group v-model:show="setGroup" :selectionList="selectionList" @confirm="refreshTaskList"
      @cancel="setGroup = false"></set-group>
    <exportData v-model:show-dialog="showExportData" :search-data="searchForm" title="任务管理" export-type="taskInfoExport">
    </exportData>
  </main-content>
</template>
<script lang="ts">
export default {
  name: 'TaskCategory'
}
</script>
<script lang="ts" setup>
import exportData from "@/components/exportData/exportData.vue";
import { Ref, UnwrapNestedRefs } from "vue";
import { ITaskCategoryItem, ITaskListData, ITaskListItem } from "@/api/modules/taskCenter";
import CategoryEditDialog from "@/views/taskCenter/components/CategoryEditDialog.vue";
import TaskEditDialog from "@/views/taskCenter/components/TaskEditDialog.vue";
import SetGroup from "@/views/taskCenter/components/SetGroup.vue"
import { Plus } from "@element-plus/icons-vue";
import {
  changeTaskStatus,
  checkTaskQuotation,
  deleteCategory,
  deleteTask,
  getTaskCategory, getTaskCategoryTree,
  updateTaskCateStatus
} from "@/api/taskCenter";
import { useTaskType } from "@/views/taskCenter/compositions/useTaskType";
import moment from "moment/moment";
import { ElMessage } from "element-plus";
import { useExternalConfigList } from "@/views/taskCenter/compositions/useExternalConfigList";
import { async } from '@antv/x6/lib/registry/marker/async';

const router = useRouter()
const route = useRoute()
const showExportData = ref(false)
const searchForm: UnwrapNestedRefs<ITaskListData> = reactive({
  taskName: '',
  taskType: '', // 任务类型
  categoryId: null, // 任务分类
  status: null,
  // insId: null, // 所属机构
})
const taskTableRef = ref()
// 任务类型查询条件 选项
const { taskTypeList, getTaskTypeLabel } = useTaskType()

const operatingRow: Ref = ref()
const editDialogMode: Ref<'edit' | 'create'> = ref('edit')

// 任务状态查询条件 选项
const taskStatus = ref([{
  label: '启用',
  value: 1,
}, {
  label: '停用',
  value: 0
}])

const formatTime = (value: number) => {
  return moment(value).format('YYYY-MM-DD HH:mm:ss')
}

const _changeTaskStatus = async (rowData: ITaskListItem) => {
  rowData.statusLoading = true
  const rs = await changeTaskStatus({ id: rowData.id })
  rowData.statusLoading = false

  return rs.code === 200
}

// 编辑新增分类
const isShowCategoryEditDialog: Ref<boolean> = ref(false)
const createCategory = (rowData: ITaskCategoryItem, node: { level: number }) => {
  if (node && node.level >= 3) {
    ElMessage.error('最多创建3级分类')
    return
  }

  editDialogMode.value = 'create'
  isShowCategoryEditDialog.value = true
  operatingRow.value = rowData
}

const editCategory = (rowData: ITaskCategoryItem) => {
  editDialogMode.value = 'edit'
  isShowCategoryEditDialog.value = true
  operatingRow.value = rowData
}

// 编辑新增任务
const isShowTaskEditDialog: Ref<boolean> = ref(false)
const createTask = () => {
  editDialogMode.value = 'create'
  isShowTaskEditDialog.value = true
  operatingRow.value = undefined
}

const editTask = (rowData: ITaskListItem) => {
  editDialogMode.value = 'edit'
  isShowTaskEditDialog.value = true
  operatingRow.value = rowData
}

const _deleteTask = (rowData: ITaskListItem) => {
  ElMessageBox.confirm('确认删除？', '提示').then(async () => {
    const rs = await deleteTask({ id: rowData.id, name: rowData.taskName })

    if (rs.code === 200) {
      ElMessage.success('删除成功')
      refreshTaskList()
    }
  })
}

const goTaskRecord = (rowData: ITaskListItem) => {
  router.push({
    path: 'task_record',
    query: {
      taskName: rowData.taskName
    }
  })
}

const treeProps = ref({
  label: "categoryName",
});
const LeftTreeRef = ref();
const treeCurrentId = ref();
const disableSelect = ref(false); // 禁止选中
const defaultExpandedKeys = ref([] as any);
const getTreeNodeId = (node: any) => {
  // console.log('getTreeNodeId', node)
  searchForm.categoryId = node.id
};

// 查询分类
const categoryList = ref<ITaskCategoryItem[]>([])
const categorySearchForm = reactive({
  categoryName: ''
})
const _getTaskCategoryTree = async () => {
  const rs = await getTaskCategoryTree(categorySearchForm)

  if (rs.code === 200) {
    categoryList.value = rs.payload ?? []
    nextTick(() => {
      LeftTreeRef.value.setCurrentKey(categoryList.value?.[0].id);  // 设置选中
      searchForm.categoryId = categoryList.value?.[0].id // 触发表格搜索
    })
  }
}

// 对接系统
const { externalConfigList, getExternalConfigList, getExternalConfigLabel } = useExternalConfigList()

const getCategoryName = (rowData: ITaskListItem) => {
  const { categoryIds } = rowData
  if (!categoryIds) {
    return ''
  } else {
    return categoryList.value
      .filter(item => categoryIds.find(id => item.id === id))
      .map(item => item.categoryName)
      .join(',')
  }
}

const _deleteCate = async (rowData: ITaskCategoryItem) => {
  const rs = await deleteCategory({ id: rowData.id })

  if (rs.code === 200) {
    ElMessage.success('删除成功')
    refresh()
  }
}

// 切换分类状态
const _changeCateStatus = async (rowData: ITaskCategoryItem) => {
  if (rowData.status) {
    const rs = await checkTaskQuotation({ id: rowData.id })
    if (rs.code === 200) {
      if (rs.payload?.aBoolean) {
        ElMessageBox.confirm(rowData.categoryName + '已被引用，停用后则任务将领取失败', '提示', {
          confirmButtonText: '确认停用',
          cancelButtonText: '取消'
        }).then(async () => {
          const rs = await updateTaskCateStatus({ id: rowData.id })
          if (rs.code === 200) {
            ElMessage.success('停用成功')
            _getTaskCategoryTree()
          }
        })
      } else {
        ElMessageBox.confirm('确认停用？', '提示', {
          confirmButtonText: '确认停用',
          cancelButtonText: '取消'
        }).then(async () => {
          const rs = await updateTaskCateStatus({ id: rowData.id })
          if (rs.code === 200) {
            ElMessage.success('停用成功')
            _getTaskCategoryTree()
          }
        })
      }
    }
  } else {
    const rs = await updateTaskCateStatus({ id: rowData.id })
    if (rs.code === 200) {
      ElMessage.success('启用成功')
      _getTaskCategoryTree()
    }
  }
}

const refresh = () => {
  _getTaskCategoryTree()
}

const refreshTaskList = () => {
  taskTableRef.value?.research()
}

// 关闭了任务列表组件的主动加载，通过改变这个值（任意数值）触发更新
const taskTableManullySearch = ref(0)

const selectionList: Ref<ITaskCategoryItem[]> = ref([])
const selectionChange = (val: ITaskCategoryItem[]) => {
  selectionList.value = val
}

const setGroup = ref(false)
const toSetGroup = () => {
  if (!selectionList.value.length) {
    ElMessage.warning("请先选择需要修改的分组");
    return;
  }
  setGroup.value = true;
}

const store = useStore();
// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  async () => {
    await _getTaskCategoryTree();
    await getExternalConfigList();
    refreshTaskList();
  },
  {
    deep: true
  }
)

onMounted(async () => {
  await _getTaskCategoryTree()
  await getExternalConfigList()

  // taskTableManullySearch.value = 1
})

</script>

<style scoped lang="scss">
.side-title-inner {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
}

.category-item {
  margin-top: 6px;
}

.category-item__offline {
  color: #999;
}
</style>
